Ext.define('Baoy.controller.system.role.SystemRoleController', {
	extend : 'Ext.app.ViewController',
	alias : 'controller.system-role-controller',

	onAddRole : function(btn, e) {
		var grid = this.getView();
		if (!grid.editRoleWin) {
			grid.editRoleWin = Ext.create('Baoy.view.system.role.SystemRoleEditView');
		}
		grid.editRoleWin.getViewModel().set('windowTitle', '新增用户');
		var dataForm = grid.editRoleWin.down('form').getForm();
		dataForm.reset();
		grid.editRoleWin.show();
	},

	onEditRole : function(btn, e) {
		var grid = this.getView(), selectRows = grid.getSelection();
		if (selectRows && selectRows.length > 0) {
			selectRow = selectRows[0];
			if (!grid.editRoleWin) {
				var editRoleWin = Ext.create('Baoy.view.system.role.SystemRoleEditView');
				editRoleWin.parentGrid = grid;
				grid.editRoleWin = editRoleWin;
			}
			var resourceTree = grid.editRoleWin.lookup('resourceTree');
			var resources = http_get('/resource/role/' + selectRow.data.id);
			if (resources) {
				var rs = Ext.decode(resources);
				if (rs && rs.length > 0) {
					var resourceIds = [];
					Ext.each(rs, function(r) { resourceIds.push({ id : r }); });
					Ext.defer(function() {
						resourceTree.setValue(resourceIds);
					}, 500, this);
				}
			}
			grid.editRoleWin.getViewModel().set('windowTitle', '修改用户');
			var dataForm = grid.editRoleWin.down('form').getForm();
			dataForm.reset();
			dataForm.loadRecord(selectRow);
			grid.editRoleWin.show();
		}
	},

	onRemoveRole : function(btn, e) {
		Ext.MessageBox.confirm('Confirm', 'Are you sure you want to do that?',
				function(optional) {
					if (optional == 'yes') {
						var grid = this.getView();
						grid.getStore().remove(grid.getSelection());
						grid.getView().refresh();
					}
				}, this);
	},

	onRowDblClick : function(me, record, element, rowIndex, e, eOpts) {
		this.onEditRole()
	},

	onChangeAvailable : function(el, rowIndex, isChecked, record) {
		console.info(record.data);
		Ext.info('修改成功！')
	},

	onSaveRole : function(btn, e) {
		var self = this;
		var form = this.getView().down('form').getForm();
		if (form.isValid()) {
			form.submit({
				success : function(form, action) {
					if (action.result.success) {
						self.getView().hide();
					}
					Ext.info(action.result.msg);
				},
				failure : function(form, action) {
					Ext.error(action.result.msg);
				}
			});
		}
	},
	
	onHideRefresh : function() {
		var editWin = this.getView();
		editWin.parentGrid.getStore().reload();
	}
})